import * as fs from 'fs'
import {HMModule} from "./HMModule";
import HandleBars from 'handlebars'
import ts from 'ohos-typescript'
import { HvigorCommonConst, HvigorNode, HvigorBuildConst } from '@ohos/hvigor'
import {FileNode,  Traverser} from "./lib/Traverse";

function handleRepeatImage() {
    let allModule = HMModule.allModules().filter(e => e.hasResource)
    allModule.forEach(e => {
        let res = e.handleRepeatImage()
        if (res.length > 0) {
            console.log(`module: ${e.name} has repeat image:`)
            console.log(res)
        }
    });
}

function handleUnusedImage() {
    let allModule = HMModule.allModules()
    let unusedData = []
    for (let module of allModule) {
        if (!module.hasResource) { continue }
        let ims = module.allImageResource
        let imgSet: Set<string> = new Set()
        module.traverseEtsFile(e => {
            const codeString = fs.readFileSync(e, 'utf-8');
            const pattern = /\$r\(['"]app\.media\.([a-zA-Z0-9_]+)['"]\)/g;
            const matches = [...codeString.matchAll(pattern)];
            const resourceNames = matches.map(match => match[1]);
            resourceNames.forEach(e => {
                imgSet.add(e)
            })
        })
        ims = ims.filter(e => !imgSet.has(e.nameWithoutExt))
        let data = {
            module: module.name,
            list: ims
        }
        unusedData.push(data)
    }
    return unusedData
}


handleRepeatImage()
//handleUnusedImage()

function render(filePath: string, distPath: string =  './report.html') {
    let tempContent = fs.readFileSync(filePath, 'utf8')
    let temp = HandleBars.compile(tempContent)
    let data = handleUnusedImage()
    let res = temp({unUsedImage: data})
    fs.writeFileSync(distPath, res)
}
/*render('./template/report.html')
import ts from 'ohos-typescript'
let content = fs.readFileSync('../code/COAgentDetailPage.ets', 'utf-8')
const rootNode = ts.createSourceFile('COAgentDetailPage.ets', content, ts.ScriptTarget.ESNext)
const traverse = (node: ts.Node) => {
    if (ts.isCallExpression(node)) {
        console.info(node.kind, node.getText(rootNode));
    }
    ts.forEachChild(node, e => {
        traverse(e)
    })
}
traverse(rootNode)
let state = ts.factory.createTryStatement(
    ts.factory.createBlock([ts.factory.createEmptyStatement()]),
    ts.factory.createCatchClause('error', ts.factory.createBlock([])),
    undefined
)*/



/*console.log(HvigorCommonConst.BUILD_PROFILE_FILE_NAME)
console.log(HvigorCommonConst.BUILD_FILE_NAME_SUFFIX)
console.log(HvigorCommonConst.BUILD_PROFILE_FILE)
console.log(HvigorCommonConst.BUILD_FILE_NAME)
console.log(HvigorCommonConst.PACKAGE_JSON)
console.log(HvigorCommonConst.HVIGOR_CONFIG_FILE_NAME)
console.log(HvigorCommonConst.HVIGOR_CONFIG_FILE_NAME_SUFFIX)
build-profile
[ '.ts', '.js', '.cjs', '.mjs' ]
build-profile.json5
hvigorfile
package.json
hvigorconfig
[ '.ts', '.js', '.cjs', '.mjs' ]*/
function compile(fileName: string[], options: ts.CompilerOptions): void {
    let program = ts.createProgram(fileName, options)
    let emitResult = program.emit()
    let allDiagnostics = ts
        .getPreEmitDiagnostics(program)
        .concat(emitResult.diagnostics)
    allDiagnostics.forEach(diagnostic => {
        if (diagnostic.file) {
            let { line, character } = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start!)
            let message = ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n')
            console.log(`${diagnostic.file.fileName} (${line + 1}, ${character + 1}): ${message}`)
        } else {
            console.log(ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'))
        }
    })
    let exitCode = emitResult.emitSkipped ? 1 : 0
    console.log(`process exit with code ${exitCode}`)
    process.exit(exitCode)
}

/*const traverser = new Traverser(new FileNode('./'))
traverser.action = console.log
traverser.filter = (e) => e.endsWith('html')
traverser.traverse()*/